package com.heima.search.service.impl;

import com.heima.common.exception.CustException;
import com.heima.feigns.BehaviorFeign;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.HistorySearchDto;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.search.pojos.ApUserSearch;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.utils.threadlocal.AppThreadLocalUtils;
import com.heima.search.service.ApUserSearchService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ApUserSearchServiceImpl implements ApUserSearchService {

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    BehaviorFeign behaviorFeign;

    /**
     * 保存用户搜索历史记录
     *
     * @param userSearchDto
     */
    @Async("taskExecutor")
    @Override
    public void insert(UserSearchDto userSearchDto) {
        String searchWords = userSearchDto.getSearchWords();
        Integer entryId = userSearchDto.getEntryId();
        if (entryId == null || StringUtils.isBlank(searchWords)) {
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //获取行为实体
        ApBehaviorEntry behaviorEntry = behaviorFeign.findByUserIdOrEquipmentId(entryId, userSearchDto.getEquipmentId()).getData();
        if (behaviorEntry == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        log.info("ApUserSearchServiceImpl insert entryId:{}, searchWords:{}", entryId, searchWords);

        ApUserSearch apUserSearch = mongoTemplate.findOne(Query.query(Criteria
                        .where("entryId").is(entryId.toString())
                        .and("keyword").is(searchWords)),
                ApUserSearch.class);
        //存在则更新，不存在新增
        if (apUserSearch != null) {
            apUserSearch.setCreatedTime(new Date());
            mongoTemplate.save(apUserSearch);
            return;
        }
        apUserSearch = new ApUserSearch();
        apUserSearch.setCreatedTime(new Date());
        apUserSearch.setEntryId(entryId.toString());
        apUserSearch.setKeyword(searchWords);
        mongoTemplate.save(apUserSearch);
    }

    /**
     * 查询用户搜索历史记录  显示10条
     * @param userSearchDto
     * @return
     */
    @Override
    public ResponseResult findUserSearch(UserSearchDto userSearchDto) {
        if(userSearchDto.getMinBehotTime() == null){
            userSearchDto.setMinBehotTime(new Date());
        }
        int size = 10;
        ApUser user = AppThreadLocalUtils.getUser();
        ResponseResult<ApBehaviorEntry> responseResult = behaviorFeign.findByUserIdOrEquipmentId(user == null ? null : user.getId(), userSearchDto.getEquipmentId());
        if (responseResult.getCode().intValue() != 0){
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,responseResult.getErrorMessage());
        }
        ApBehaviorEntry behaviorEntry = responseResult.getData();
        if (behaviorEntry == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        List<ApUserSearch> userSearchList = mongoTemplate.find(Query.query(Criteria
                        .where("entryId").is(behaviorEntry.getRefId().toString())
                        .and("createdTime")
                        .lt(userSearchDto.getMinBehotTime()))
                        .with(Sort.by(Sort.Direction.DESC, "createdTime")).limit(size)
                , ApUserSearch.class);
        return ResponseResult.okResult(userSearchList);
    }
    @Override
    public ResponseResult delUserSearch(HistorySearchDto historySearchDto) {
        if(historySearchDto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUser user = AppThreadLocalUtils.getUser();
        ApBehaviorEntry behaviorEntry = behaviorFeign.findByUserIdOrEquipmentId(user == null ? null : user.getId(), historySearchDto.getEquipmentId()).getData();
        if(behaviorEntry == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"行为实体数据不存在");
        }
        mongoTemplate.remove(Query.query(Criteria.where("_id").is(historySearchDto.getId()).and("entryId").is(behaviorEntry.getRefId().toString())),ApUserSearch.class);
        return ResponseResult.okResult();
    }
}